package com.spark.util.core

import org.apache.log4j.{LogManager, PropertyConfigurator}
import org.slf4j.bridge.SLF4JBridgeHandler
import org.slf4j.impl.StaticLoggerBinder
import org.slf4j.{Logger, LoggerFactory}

trait Logging {

  private def log: Logger = LoggerFactory.getLogger(this.getClass.getName.stripSuffix("$"))

  protected def debug(msg: => String): Unit = if (log.isDebugEnabled) log.debug(msg)

  protected def info(msg: => String): Unit = if (log.isInfoEnabled) log.info(msg)

  protected def warn(msg: => String): Unit = if (log.isWarnEnabled) log.warn(msg)

  protected def error(msg: => String): Unit = if (log.isErrorEnabled) log.error(msg)
}

/**
 * 用slf4j统一管理日志并配置统一使用log4j日志
 */
object Logging{

  val LOG4J_LOGGER_FACTORY: String = "org.slf4j.impl.Log4jLoggerFactory"
  val DEFAULT_LOG_PROP: String = "org/apache/spark/log4j-defaults.properties"

  def init(): Unit = {
    SLF4JBridgeHandler.removeHandlersForRootLogger()
    SLF4JBridgeHandler.install()
    val binderClass = StaticLoggerBinder.getSingleton.getLoggerFactoryClassStr
    val usingLog4j = binderClass.equals(LOG4J_LOGGER_FACTORY)
    if(usingLog4j){
      val log4j12Initialized = LogManager.getRootLogger.getAllAppenders.hasMoreElements
      if (!log4j12Initialized) {
        val url = this.getClass.getClassLoader.getResource(DEFAULT_LOG_PROP)
        PropertyConfigurator.configure(url)
        System.err.println(s"Using Spark's default log4j profile: $DEFAULT_LOG_PROP")
      }
    }
  }
}
